package net.xiodi.devops

def GetChangeString() {
    def MAX_MSG_LEN = 100
    def changeString = ""
    def changeLogSets = currentBuild.changeSets
    for (int i = 0; i < changeLogSets.size(); i++) {
        def entries = changeLogSets[i].items
        for (int j = 0; j < entries.length; j++) {
            def entry = entries[j]
            def truncated_msg = entry.msg.take(MAX_MSG_LEN)
            def commitTime = new Date(entry.timestamp).format("yyyy-MM-dd HH:mm:ss")
            changeString += "> - {truncated_msg} [{entry.author} {commitTime}]\n"
        }
    }
    if (!changeString) {
        changeString = "> - No new changes"
    }
    return changeString
}

def DingDingReq(RobotID, Status, Version, Phone) {
    wrap([$class: 'BuildUser']) {
        def changeString = GetChangeString()
        dingtalk(
                robot: RobotID,
                type: 'ACTION_CARD',
                title: '新消息',
                text: [
                        "### ${env.JOB_NAME}",
                        "> - 构建结果：**${Status}**",
                        "> - 构建用户：**${env.BUILD_USER}**",
                        "> - 构建号码：**${env.BUILD_NUMBER}**",
                        "> - 构建版本：**${Version}**",
                        "> - 持续时间：**${currentBuild.durationString}**",
                        "> - 构建时间：**${env.BUILD_TIMESTAMP}**"
                ],
                btns: [
                        [
                                title: '构建日志',
                                actionUrl: "${env.BUILD_URL}console"
                        ],
                        [
                                title: '更改记录',
                                actionUrl: "${env.BUILD_URL}changes"
                        ]

                ],
                at: [
                        Phone
                ]
        )
    }
}